package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import restaurant.Location;

/**
 * Servlet implementation class Locations
 */
@WebServlet("/Locations")
public class Locations extends HttpServlet {
    private static final long serialVersionUID = 201211122239L;

    protected EntityManagerFactory _emf;

    private static String UNIT_NAME = "ThaiKitchen";

    @Override
    public void init(final ServletConfig config) throws ServletException {
        super.init(config);
        config.getServletContext().log("Initializing persistence unit [" + UNIT_NAME + "]");
        try {
            _emf = Persistence.createEntityManagerFactory(UNIT_NAME);
        } catch (final Exception e) {
            throw new ServletException(e);
        }
        config.getServletContext().log("Initialized with persistence unit [" + UNIT_NAME + "]");
    }

    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final String id = request.getParameter("id");

        request.setAttribute("id", id);

        final List<Location> locations = new ArrayList<Location>();

        final EntityManager em = _emf.createEntityManager();
        locations.addAll(em.createQuery("select l from Location l", Location.class).getResultList());
        em.close();

        request.setAttribute("locations", locations);

        request.setAttribute("namesToPages", getLinkMap());
        request.getRequestDispatcher(getDispatcherPage()).forward(request, response);
    }

    protected Map<String, String> getLinkMap() {
        return LinkData.getLinkMap();
    }

    protected String getDispatcherPage() {
        return "/WEB-INF/locations.jsp";
    }
}
